package com.lemon.cloud.websocket.config;

import com.lemon.cloud.websocket.holder.WebSocketSessionHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Collection;

@Slf4j
public class WebSocketMessageSender {

    /**
     * 广播信息
     * @param message
     */
    public static void broadcast(String message) {
        Collection<WebSocketSession> sessions = WebSocketSessionHolder.getSessions();
        sessions.forEach(item -> {
            send(item, message);
        });
    }

    public static boolean send(Object sessionKey, String message) {
        WebSocketSession session = WebSocketSessionHolder.getSession(sessionKey);
        if (session == null) {
            log.info("[send] 当前 sessionKey：{} 对应 session 不在本服务中", sessionKey);
            return false;
        } else {
            return send(session, message);
        }
    }

    public static boolean send(WebSocketSession session, String message) {
        if (session == null) {
            log.error("[send] session 为 null");
            return false;
        } else if (!session.isOpen()) {
            log.error("[send] session 已经关闭");
            return false;
        } else {
            try {
                session.sendMessage(new TextMessage(message));
                return true;
            } catch (IOException e) {
                log.error("[send] session({}) 发送消息({}) 异常", new Object[]{session, message, e});
                return false;
            }
        }
    }
}
